<template>
  <el-upload v-if="enable"
             v-model:file-list="fileList" @success="successUpload" @remove="removed" ref="uploader"
             :action="uploadAction" :headers="headers" @preview="handlePreview"
             :on-change="handleChange" multiple>
    <template #trigger>
      <slot name="trigger">
        <el-button round v-show="enable" icon="attachment" type="primary">上传附件</el-button>
      </slot>
    </template>
  </el-upload>
  <div v-else>
    <div v-for="file in fileList" class="f-uploader-detail-item-wrapper">
      <slot name="file" :file="file">
        <div class="left">
          <el-link @click="() => handlePreview(file)">{{ file.name }}</el-link>
        </div>
        <el-text class="right">{{ file.size }}</el-text>
      </slot>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex';
import {canPreview, isEmpty} from '@/utils/CommonUtils';
import {getAction} from '@/request/BaseRequest';

export default {
  name: 'FUploader',
  props: {
    enable: {
      type: Boolean,
      default: true
    },
    attachmentIds: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      fileList: [],
      uploadAction: `${window.baseURL}/sys/attach/upload`,
      headers: {
        'ff-token': undefined,
      }
    };
  },
  mounted() {
    this.headers['ff-token'] = this.userInfo.token;
    this.setData(this.attachmentIds);
  },
  methods: {
    setData(attachmentIds) {
      this.loadAttachmentByIds(attachmentIds);
    },
    handleChange() {

    },
    loadAttachmentByIds(attachmentIds) {
      if (isEmpty(attachmentIds)) {
        this.fileList = [];
        return;
      }
      this.loading = true;
      getAction('/sys/attach/loadAttachmentByIds', {attachmentIds}).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          this.setAttachmentsFileList(result);
        }
      });
    },
    setAttachmentsFileList(list) {
      if (isEmpty(list)) return;
      this.fileList = [];
      list.forEach(file => {
        this.fileList.push({
          name: file.attachName,
          percentage: 100,
          size: file.size,
          uid: file.id,
          response: {
            success: true,
            result: file
          }
        });
      });
    },
    handlePreview(uploadFile) {
      let attachId = uploadFile.response.result.id;
      let url = `${window.baseURL}/sys/attach/download?id=${attachId}&token=${this.userInfo.token}`;
      try {
        if (canPreview(uploadFile.response.result.ext)) {
          url = `${window.baseURL}/sys/attach/preview?id=${attachId}&token=${this.userInfo.token}`;
        }
      } catch (e) {
      }
      this.$windowManager.open(url, {title: '下载'});
    },
    removed() {
      this.$emit('attachmentChange')
    },
    successUpload(response, uploadFile, UploadFiles) {
      if (!response.success) {
        this.$message.warning(response.message);
        this.$refs.uploader.handleRemove(uploadFile);
      }
      this.$emit('attachmentChange')
    },
    getAttachmentIds() {
      let fileList = this.fileList;
      if (isEmpty(fileList)) fileList = [];
      return fileList.map(file => file?.response?.result?.id).filter(f => !!f).toString();
    },
    getAttachmentNames() {
      let fileList = this.fileList;
      if (isEmpty(fileList)) fileList = [];
      return fileList.map(file => file?.response?.result?.attachName).filter(f => !!f).toString();
    },
  },
  computed: {
    ...mapGetters('user', [
      'userInfo'
    ])
  },
  watch: {
    attachmentIds() {
      this.setData(this.attachmentIds);
    },
  }
};
</script>

<style>
.f-uploader-detail-item-wrapper {
  display: flex;

}

.f-uploader-detail-item-wrapper .left {
  flex: 1;
  text-align: left;
}

.f-uploader-detail-item-wrapper .right {
  width: 120px;
  text-align: right;
}

</style>
